package com.ztt.vxchat.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.Scheduler;
import cn.hutool.cron.task.Task;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ztt.vxchat.timer.TaskTimer;
import com.ztt.vxchat.utils.CheckoutUtil;
import com.ztt.vxchat.utils.ToolsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ztt
 * @project_name vx-chat
 * @description []
 * @date 2022/8/22 20:49
 */
@RequestMapping("/vx/api")
@RestController
public class VXController {


    @Value("${custom-default.vx-config}")
    String vxConfigDefaultContent;

    @Value("${custom-default.message}")
    String messageDefaultContent;






    @RequestMapping("/vxConfig")
    public Object vxConfig(String content){


        JSONObject vxConfigJson = null;
        try {
            vxConfigJson = JSONUtil.parseObj(content);
        }catch (JSONException e){
            return "json格式错误";
        }


        String vxConfigPath = ToolsUtil.getNowProjectPath()+"/vx-config.json";

        FileUtil.writeUtf8String(content,vxConfigPath);

        return "提交成功";
    }


    @RequestMapping("/messageConfig")
    public Object messageConfig(String content){

        JSONArray vxConfigJson = null;
        try {
            vxConfigJson = JSONUtil.parseArray(content);
        }catch (JSONException e){
            return "json格式错误";
        }


        String messagePath = ToolsUtil.getNowProjectPath()+"/message.json";

        FileUtil.writeUtf8String(content,messagePath);

        return "提交成功";
    }


    @RequestMapping("/tokenConfig")
    public Object tokenConfig(String content){

        String tokenPath = ToolsUtil.getNowProjectPath()+"/access-token.json";

        FileUtil.writeUtf8String(content,tokenPath);

        return "提交成功";
    }







    @RequestMapping("/init")
    public Object init(){

        String vxConfigPath = ToolsUtil.getNowProjectPath()+"/vx-config.json";
        String tokenPath = ToolsUtil.getNowProjectPath()+"/access-token.json";
        String messagePath = ToolsUtil.getNowProjectPath()+"/message.json";

//        初始化TOKEN
        FileUtil.writeUtf8String("",tokenPath);
//        初始化配置文件
        FileUtil.writeUtf8String(JSONUtil.formatJsonStr(vxConfigDefaultContent),vxConfigPath);
//        初始化消息配置文件
        FileUtil.writeUtf8String(JSONUtil.formatJsonStr(messageDefaultContent),messagePath);


        return "初始化成功";
    }







    @RequestMapping("/stopTimer")
    public Object stopTimer(){

        //        停止所有定时任务
        List<Task> tasks = CronUtil.getScheduler().getTaskTable().getTasks();
        try{
            if(tasks.size() > 0){
                CronUtil.stop();
            }
        }catch (IllegalStateException e){
            System.out.println("没有运行中的定时任务");
        }

        return "已停止所有定时任务";
    }




    @RequestMapping("/resetTimer")
    public Object resetTimer(){

        new TaskTimer().start();

        return "操作成功";
    }



    @RequestMapping("/checkSignature")
    public Object checkSignature(String signature,String timestamp,String nonce,String echostr) {

        System.out.println("signature:"+signature+"---timestamp:"+timestamp+"---nonce:"+nonce+"---echostr:"+echostr);

        if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }

        return false;
    }




    @RequestMapping("/getToken")
    public Object getToken() {

        String vxConfigPath = ToolsUtil.getNowProjectPath()+"/vx-config.json";


        FileReader fileReader = null;
        try {
            fileReader= new FileReader(vxConfigPath);
        }catch (IORuntimeException e) {
            return "获取失败，请先初始化配置文件";
        }

        String vxConfig = fileReader.readString();
        JSONObject vxConfigJson = null;
        try {
            vxConfigJson = JSONUtil.parseObj(vxConfig);
        }catch (JSONException e){
            return "配置文件错误，请检查或重新初始化配置文件";
        }

        String appid = vxConfigJson.getStr("appid");
        String secret = vxConfigJson.getStr("secret");

        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type","client_credential");
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);


        //链式构建请求
        String result = HttpRequest.get(url)
                .header(Header.USER_AGENT, "ztt")//头信息，多个头信息多次调用此方法即可
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
//        Console.log(result);

        JSONObject formatResult = JSONUtil.parseObj(result);

        String ACCESS_TOKEN = formatResult.getStr("access_token");

        Console.log("获取到ACCESS_TOKEN"+ACCESS_TOKEN);


        String tokenPath = ToolsUtil.getNowProjectPath()+"/access-token.json";

        if(!StrUtil.hasBlank(ACCESS_TOKEN)){
            FileUtil.writeUtf8String(ACCESS_TOKEN,tokenPath);
        }

        return StrUtil.hasBlank(ACCESS_TOKEN) ? "获取失败，请检查appid和secret是否正确" : ACCESS_TOKEN;
    }



    @RequestMapping("/sendTemplateMessage")
    public Object sendTemplateMessage(JSONObject paramJson) {

        String tokenPath = ToolsUtil.getNowProjectPath()+"/access-token.json";

        FileReader fileReader = null;
        try {
            fileReader= new FileReader(tokenPath);
        }catch (IORuntimeException e) {
            return "获取失败，请先初始化配置文件";
        }

        String TOKEN = fileReader.readString();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+TOKEN;


        Console.log(paramJson.toString());

        //链式构建请求
        String result = HttpRequest.post(url)
                .header(Header.USER_AGENT, "ztt")//头信息，多个头信息多次调用此方法即可
                .body(paramJson.toString())
                .timeout(20000)//超时，毫秒
                .execute().body();

        Console.log(result);

        return result;
    }




    @RequestMapping("/testSendTemplateMessage")
    public Object testSendTemplateMessage(String templateId,String openID) {

        String tokenPath = ToolsUtil.getNowProjectPath()+"/access-token.json";

        FileReader fileReader = null;
        try {
            fileReader= new FileReader(tokenPath);
        }catch (IORuntimeException e) {
            return "获取失败，请先初始化配置文件";
        }

        String TOKEN = fileReader.readString();

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+TOKEN;


        JSONObject paramJson = JSONUtil.createObj();
        paramJson.set("touser",openID);
        paramJson.set("template_id",templateId);


        //链式构建请求
        String result = HttpRequest.post(url)
                .header(Header.USER_AGENT, "ztt")//头信息，多个头信息多次调用此方法即可
                .body(paramJson.toString())
                .timeout(20000)//超时，毫秒
                .execute().body();

        Console.log(result);

        return result;
    }



}
